package org.footito.android.activity;

import java.io.IOException;

import org.footito.android.R;
import org.footito.android.data.update.UpdateListener;
import org.footito.android.data.update.Waiter;
import org.footito.android.tools.Tools;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

abstract class Loader extends Activity implements UpdateListener {
	private static void launchActivityForResult(Activity context, int requestCode) {
		Intent intent = new Intent(context, Loader.class);
		context.startActivityForResult(intent, requestCode);
	}

	private TextView progress;
	private Waiter waiter = new Waiter(this, this);
	private String lastText;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (!waiter.isCancelled())
			waiter.cancel(true);
		finish();
	}

	@Override
	public void onComplete() {
		Log.d("Footito", "Finished");
		finish();
		// Intent intent = new Intent(Loader.this, Timeline.class);
		// startActivityForResult(intent, 0);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loader);

		progress = (TextView) findViewById(R.id.TextProgress);

		Tools.checkFilesFolder();
		waiter.execute(new Void[0]);
	}

	@Override
	public void onError(Exception e) {
		if (e instanceof IOException) {
			Toast.makeText(this, getResources().getString(R.string.nonetwork), Toast.LENGTH_SHORT)
					.show();
		}
		finish();
	}

	@Override
	protected void onPause() {
		super.onPause();
		waiter.cancel(true);
	}

	@Override
	public void onProgress(Integer... progressId) {
		// Log.d("Footito", "Publish : " + progressId[0]);
		if (UpdateListener.DATACACHING == progressId[0]) {
			progress.setText(getResources().getString(R.string.caching));
			lastText = "";
		} else if (UpdateListener.UPDATESTARTED == progressId[0]) {
			progress.setText(getResources().getString(R.string.updating));
		} else if (UpdateListener.COMMENTSLOADINGSTARTED == progressId[0]) {
			lastText = getResources().getString(R.string.chargingcomments);
			progress.setText(lastText);
		} else if (UpdateListener.TEAMLOADINGSTARTED == progressId[0]) {
			lastText = getResources().getString(R.string.chargingteams);
			progress.setText(lastText);
		} else if (UpdateListener.EVENTLOADINGSTARTED == progressId[0]) {
			lastText = getResources().getString(R.string.chargingevents);
			progress.setText(lastText);
		} else if (UpdateListener.DOWNLOAD_PROGRESS == progressId[0]) {
			progress.setText(lastText + " (" + progressId[1] + "%)");
		} else if (UpdateListener.COMMENTSLOADINGOK == progressId[0]) {
			lastText = getResources().getString(R.string.commentsloaded);
			progress.setText(lastText);
		}
		// Log.d("Footito", "Published : " + progressId[0]);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}